package diploma.kisel.modelas.gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import diploma.kisel.modelas.domain.Role;
import diploma.kisel.modelas.domain.User;
import diploma.kisel.modelas.service.RoleServiceImpl;
import diploma.kisel.modelas.service.UserServiceImpl;
import diploma.kisel.modelas.service.api.RoleService;
import diploma.kisel.modelas.service.api.UserService;
import diploma.kisel.modelas.validation.Validation;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;

/**
 * This window is used to register users.
 * 
 * @author Nikolay Kisel
 *
 */
public class RegistrationWindow extends JFrame {

	private final int loginLength = 20;
	private final int passwordLength = 45;
	private final int nameLength = 30;
	private final int surnameLength = 30;
	private final int groupLength = 10;

	private JPanel contentPane;
	private JTextField textFieldLogin;
	private JPasswordField passwordField;
	private JTextField textFieldName;
	private JTextField textFieldSurname;
	private JTextField textFieldGroup;

	private final String studentRole = "Студент";
	
	private static RegistrationWindow frame;

	private UserService userService = new UserServiceImpl();
	
	private RoleService roleService = new RoleServiceImpl();

	
	/**
	 * Create the frame.
	 */
	public RegistrationWindow() {
		setTitle("Регистрация");
//		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 381, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		SpringLayout sl_contentPane = new SpringLayout();
		contentPane.setLayout(sl_contentPane);

		JLabel label = new JLabel("Логин:");
		sl_contentPane.putConstraint(SpringLayout.NORTH, label, 10,
				SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, label, 10,
				SpringLayout.WEST, contentPane);
		contentPane.add(label);

		textFieldLogin = new JTextField();
		sl_contentPane.putConstraint(SpringLayout.NORTH, textFieldLogin, -3, SpringLayout.NORTH, label);
		sl_contentPane.putConstraint(SpringLayout.WEST, textFieldLogin, 97, SpringLayout.EAST, label);
		sl_contentPane.putConstraint(SpringLayout.EAST, textFieldLogin, -5, SpringLayout.EAST, contentPane);
		contentPane.add(textFieldLogin);
		textFieldLogin.setColumns(10);

		JLabel label_1 = new JLabel("Пароль:");
		sl_contentPane.putConstraint(SpringLayout.NORTH, label_1, 24,
				SpringLayout.SOUTH, label);
		sl_contentPane.putConstraint(SpringLayout.WEST, label_1, 0,
				SpringLayout.WEST, label);
		contentPane.add(label_1);

		passwordField = new JPasswordField();
		sl_contentPane.putConstraint(SpringLayout.NORTH, passwordField, -3, SpringLayout.NORTH, label_1);
		sl_contentPane.putConstraint(SpringLayout.WEST, passwordField, 0, SpringLayout.WEST, textFieldLogin);
		sl_contentPane.putConstraint(SpringLayout.EAST, passwordField, 0, SpringLayout.EAST, textFieldLogin);
		passwordField.setColumns(10);
		contentPane.add(passwordField);

		JLabel lblNewLabel = new JLabel("Имя:");
		sl_contentPane.putConstraint(SpringLayout.NORTH, lblNewLabel, 26,
				SpringLayout.SOUTH, label_1);
		sl_contentPane.putConstraint(SpringLayout.WEST, lblNewLabel, 0,
				SpringLayout.WEST, label);
		contentPane.add(lblNewLabel);

		textFieldName = new JTextField();
		sl_contentPane.putConstraint(SpringLayout.NORTH, textFieldName, -3, SpringLayout.NORTH, lblNewLabel);
		sl_contentPane.putConstraint(SpringLayout.WEST, textFieldName, 0, SpringLayout.WEST, textFieldLogin);
		sl_contentPane.putConstraint(SpringLayout.EAST, textFieldName, 0, SpringLayout.EAST, textFieldLogin);
		contentPane.add(textFieldName);
		textFieldName.setColumns(10);

		JLabel label_2 = new JLabel("Фамилия:");
		sl_contentPane.putConstraint(SpringLayout.NORTH, label_2, 24,
				SpringLayout.SOUTH, lblNewLabel);
		sl_contentPane.putConstraint(SpringLayout.WEST, label_2, 0,
				SpringLayout.WEST, label);
		contentPane.add(label_2);

		textFieldSurname = new JTextField();
		sl_contentPane.putConstraint(SpringLayout.NORTH, textFieldSurname, -3, SpringLayout.NORTH, label_2);
		sl_contentPane.putConstraint(SpringLayout.WEST, textFieldSurname, 0, SpringLayout.WEST, textFieldLogin);
		sl_contentPane.putConstraint(SpringLayout.EAST, textFieldSurname, 0, SpringLayout.EAST, textFieldLogin);
		contentPane.add(textFieldSurname);
		textFieldSurname.setColumns(10);

		JLabel label_3 = new JLabel("Группа:");
		sl_contentPane.putConstraint(SpringLayout.NORTH, label_3, 27,
				SpringLayout.SOUTH, label_2);
		sl_contentPane.putConstraint(SpringLayout.WEST, label_3, 0,
				SpringLayout.WEST, label);
		contentPane.add(label_3);

		JLabel label_4 = new JLabel("(Если вы являетесь студентом)");
		sl_contentPane.putConstraint(SpringLayout.NORTH, label_4, 6, SpringLayout.SOUTH, label_3);
		sl_contentPane.putConstraint(SpringLayout.WEST, label_4, 0, SpringLayout.WEST, label);
		contentPane.add(label_4);

		textFieldGroup = new JTextField();
		sl_contentPane.putConstraint(SpringLayout.NORTH, textFieldGroup, -3, SpringLayout.NORTH, label_3);
		sl_contentPane.putConstraint(SpringLayout.WEST, textFieldGroup, 0, SpringLayout.WEST, textFieldLogin);
		sl_contentPane.putConstraint(SpringLayout.EAST, textFieldGroup, 0, SpringLayout.EAST, textFieldLogin);
		contentPane.add(textFieldGroup);
		textFieldGroup.setColumns(10);

		JButton button = new JButton("Отменить");
		sl_contentPane.putConstraint(SpringLayout.EAST, button, 0, SpringLayout.EAST, textFieldLogin);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				frame.setVisible(false);
			}
		});
		sl_contentPane.putConstraint(SpringLayout.SOUTH, button, 0,
				SpringLayout.SOUTH, contentPane);
		contentPane.add(button);

		JButton button_1 = new JButton("Сохранить");
		sl_contentPane.putConstraint(SpringLayout.SOUTH, button_1, 0, SpringLayout.SOUTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.EAST, button_1, -11, SpringLayout.WEST, button);
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveUser();
			}
		});
		contentPane.add(button_1);
	}

	public void saveUser() {
		User user = new User();
		String login = textFieldLogin.getText();
		if (Validation.isLengthBetween(login, 3, loginLength))
			user.setLogin(login);
		else {
			JOptionPane.showMessageDialog(frame,
					"Неправильно задан логин. Может включать от 3 до " + loginLength
							+ " символов.", "Предупреждение", JOptionPane.WARNING_MESSAGE);
			return;
		}
		String password = passwordField.getText();
		if (Validation.isLengthBetween(password, 3, passwordLength))
			user.setPassword(password);
		else {
			JOptionPane.showMessageDialog(frame,
					"Неправильно задан пароль. Может включать от 3 до "
							+ passwordLength + " симвлов.", "Предупреждение", JOptionPane.WARNING_MESSAGE);
			return;
		}
		String name = textFieldName.getText();
		if (Validation.isLengthBetween(name, 2, nameLength))
			user.setName(name);
		else {
			JOptionPane.showMessageDialog(frame,
					"Неправльно задано имя. Может включать от 3 до " + nameLength
							+ " символов.",  "Предупреждение", JOptionPane.WARNING_MESSAGE);
			return;
		}
		String surname = textFieldSurname.getText();
		if (Validation.isLengthBetween(surname, 2, surnameLength))
			user.setSurname(surname);
		else {
			JOptionPane.showMessageDialog(frame,
					"Неправильно задана фамилия(Может включать до "
							+ surnameLength + " символов" , "Предупреждение", JOptionPane.WARNING_MESSAGE);
			return;
		}
		String group = textFieldGroup.getText();
		if (Validation.isLengthBetween(group, 0, groupLength))
			user.setGroup(group);
		else {
			JOptionPane.showMessageDialog(frame,
					"Неправильно задана группа(Может отсутствовать или включать до "
							+ groupLength + " символов", "Предупреждение", JOptionPane.WARNING_MESSAGE);
			return;
		}
		Set<Role> roles = new HashSet<>();
		Role role = roleService.findById(studentRole);
		user.setRoles(roles);
		userService.save(user);
		JOptionPane.showMessageDialog(frame, "Регистрация прошла успешно.", "Сообщение", JOptionPane.INFORMATION_MESSAGE);
		frame.setVisible(false);
	}

	public static RegistrationWindow getFrame() {
		return frame;
	}

	public static void setFrame(RegistrationWindow frame) {
		RegistrationWindow.frame = frame;
	}

}
